import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { mockWords } from '@/api/mock'

export const useWordStore = defineStore('word', () => {
  // 状态
  const words = ref([])
  const favorites = ref(new Map()) // key: wordId, value: { level: 1|2, timestamp }
  const loading = ref(false)

  // 计算属性
  const favoriteWords = computed(() => {
    return words.value.filter(word => favorites.value.has(word.id))
  })

  const unfamiliarWords = computed(() => {
    return words.value.filter(word => {
      const fav = favorites.value.get(word.id)
      return fav && fav.level === 1
    })
  })

  const familiarWords = computed(() => {
    return words.value.filter(word => {
      const fav = favorites.value.get(word.id)
      return fav && fav.level === 2
    })
  })

  // 方法
  const loadWords = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      words.value = mockWords
    } catch (error) {
      console.error('加载单词失败:', error)
    } finally {
      loading.value = false
    }
  }

  const getWordById = (id) => {
    return words.value.find(word => word.id === parseInt(id))
  }

  const updateWordMeaning = (id, newMeaning) => {
    const word = words.value.find(w => w.id === parseInt(id))
    if (word) {
      word.meaning = newMeaning
    }
  }

  const toggleFavorite = (wordId, level = 1) => {
    const id = parseInt(wordId)
    if (favorites.value.has(id)) {
      const current = favorites.value.get(id)
      if (current.level === level) {
        // 如果当前级别相同，则取消收藏
        favorites.value.delete(id)
      } else {
        // 如果级别不同，则更新级别
        favorites.value.set(id, { level, timestamp: Date.now() })
      }
    } else {
      // 添加收藏
      favorites.value.set(id, { level, timestamp: Date.now() })
    }
  }

  const getFavoriteLevel = (wordId) => {
    const fav = favorites.value.get(parseInt(wordId))
    return fav ? fav.level : 0
  }

  const isFavorite = (wordId) => {
    return favorites.value.has(parseInt(wordId))
  }

  return {
    words,
    favorites,
    loading,
    favoriteWords,
    unfamiliarWords,
    familiarWords,
    loadWords,
    getWordById,
    updateWordMeaning,
    toggleFavorite,
    getFavoriteLevel,
    isFavorite
  }
})